package com.ews.onlineexchange.service.activitii;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.controller.activitii.BpmHome;
import com.ews.onlineexchange.model.assess.AssessRecord;

/**
 * @author taylover 此工具类只用于一次初始化
 */
@Named
public class AssessRecordProcessGenerator implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Inject
	EntityManager entityManager;
	private static final String QUERY_ALL_ASSESSRECORD_EQL = "" 
			+ "	SELECT 	rec 					"
			+ " FROM 	AssessRecord rec		"
			+ " WHERE 	rec.delFlag = '0' 		";
			
	
	public void check() {
		Session session = entityManager.unwrap(Session.class);
		ScrollableResults sr = session.createQuery(QUERY_ALL_ASSESSRECORD_EQL).setCacheMode(CacheMode.IGNORE)
				.scroll(ScrollMode.FORWARD_ONLY);

		while (sr.next()) {
			AssessRecord rec = (AssessRecord) sr.get(0);
			startSupplierAssessRecordProcess(rec);
		}
	}
	@Inject
	BpmHome						bpmHome;

	@Inject
	RuntimeService				runtimeService;

	@Inject
	TaskService					taskService;
	@SuppressWarnings( "unchecked" )
	private void startSupplierAssessRecordProcess(AssessRecord rec) {
		Task task = null;
		String username = rec.getServiceSupplier().getUsername();
		if ( StringUtils.isBlank( bpmHome.getTaskId() ) ) {
			HashMap<String, Object> variables = new HashMap<String, Object>();
			variables.put( "initiator", username );
			variables.put( "dictId", rec.getDict().getId() );
			variables.put( "assessRecordId", rec.getId() );
			variables.put( "periodTypeName", rec.getDict().getPeriodType().name() );
						
			Map beanMap = new BeanMap( rec );			
			variables.putAll( beanMap );
			
			ProcessInstance process = runtimeService.startProcessInstanceByKey( "supplierAssessRecordAudit", rec.getId(), variables );			
			
			List<Task> list = taskService.createTaskQuery().processInstanceId( process.getId() ).list();
			task = list.get( 0 );			
		} else {
			task = taskService.createTaskQuery().taskId( bpmHome.getTaskId() ).singleResult();
		}
		
		taskService.claim( task.getId(), username );
		taskService.complete( task.getId() );
	}
	
}
